<template>
  <div class="search-suggestion">
    <van-cell v-for="(v, i) in suggestions" :key="i" :title="v" icon="search" />
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
    }
  },
  watch: {
    searchText: {
      // 监视的处理函数
      // handler(val) {
      //   this.loadSearchSuggestion(val)
      // },
      // debounce 函数
      // 参数1：函数
      // 参数2：防抖时间
      // 返回值：防抖之后的函数，和参数1功能是一样的
      handler: debounce(function (val) {
        this.loadSearchSuggestion(val)
      }, 300),
      // 首次监视触发
      immediate: true,
    },
  },
  methods: {
    loadSearchSuggestion(q) {
      getSearchSuggestion(q)
        .then(({ data }) => {
          this.suggestions = data.data.options.filter(v => !!v)
        })
        .catch(() => {
          this.$toast('获取失败')
        })
    },
  },
}
</script>
